package br.com.condominio.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import br.com.condominio.controller.UsuarioBean;
import br.com.condominio.entity.Usuario;

public class UsuarioConverter implements Converter {

    @SuppressWarnings({ "static-access", "deprecation" })
	public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {

    	if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                String string = submittedValue;
				UsuarioBean bean =  (UsuarioBean) FacesContext.getCurrentInstance().getApplication().createValueBinding("#{usuarioBean}").getValue(facesContext.getCurrentInstance());
                
                for (Usuario o : bean.getUsuarios()) {
                    if (o.getUseLogin().equalsIgnoreCase(string)) {
                        return o;
                    }
                }

            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Usuario inválido"));
            }
        }

        return null;
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return ((Usuario) value).getUseLogin();
        }
    }
}
